package com.itrip.controller;

import com.itrip.document.Hotel;
import com.itrip.dto.HotelDetail;
import com.itrip.dto.ResponseDTO;
import com.itrip.pojo.ItripHotelOrder;
import com.itrip.pojo.ItripHotelTempStore;
import com.itrip.pojo.ItripUser;
import com.itrip.service.HotelService;
import com.itrip.vo.hotel.BookingHotelVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Api(tags = "酒店查询")
@RestController
public class HotelController {
    @Resource
    private HotelService hotelService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;


    /**
     * 查询酒店
     * @param keyWord
     * @param startPage
     * @param pageSize
     * @return
     * @throws IOException
     * @throws SolrServerException
     */
    @ApiOperation("用于分页旅馆查询")
    @GetMapping( "/getHotel" )
    @ApiImplicitParams({
            @ApiImplicitParam(name = "keyWord",value = "关键词"),
            @ApiImplicitParam(name="startPage",value = "开始的页码"),
            @ApiImplicitParam(name="pageSize",value = "每页查询个数")
    })
    public ResponseDTO getHotel(String keyWord, Integer startPage , Integer pageSize) throws IOException, SolrServerException {
        List<Hotel> hotel = hotelService.getHotel(keyWord, (startPage - 1) * pageSize, pageSize);
        return new ResponseDTO(100,"获取旅馆成功",hotel);
    }


    @ApiOperation("获取旅馆数量")
    @ApiImplicitParam(name="keyWord",value = "关键词")
    @GetMapping("/getHotelNum")
    public ResponseDTO getHotelNum(String keyWord) throws IOException, SolrServerException {
       int num= hotelService.getHotelNum(keyWord);
        return new ResponseDTO(100,"旅馆查询数量",num);
    }

    @GetMapping( "/getHotelDetail" )
    @ApiOperation("获取酒店详细信息")
    @ApiImplicitParam(name = "id",value = "酒店id")
    public ResponseDTO getHotelDetail(Integer id) throws IOException, SolrServerException {
        List<HotelDetail> hotelDetailList= hotelService.getHotelDetail(id);
        return new ResponseDTO(100,"获取旅馆成功",hotelDetailList);
    }

    @GetMapping("/view/getRestRoom")
    @ApiOperation("获取酒店的床房的剩余数量及其他信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name="token",value = "token",required = true,dataType = "String",paramType = "header"),
            @ApiImplicitParam(name="hotelId",value="酒店id",example = "1"),
            @ApiImplicitParam(name="roomId",value="床房id",example = "2")
    })
    public ResponseDTO getRestRoom(Integer hotelId, Integer roomId/*, HttpServletRequest request*/){
        int num=hotelService.getRestRoom( hotelId, roomId);
        return new ResponseDTO(100,"????",num);
    }






    @PostMapping("/view/bookHotel")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("预订酒店")
    @ApiImplicitParams({
            @ApiImplicitParam(name="token",value = "token",required = true,dataType = "String",paramType = "header"),
    })
    public ResponseDTO bookHotel(BookingHotelVo bookingHotelVo, HttpServletRequest request){
        /*
        订单库中添加
        订单记录中添加
        hotel旅馆中数量减少
        给定下单过期时间
        * */
         ItripHotelOrder itripHotelOrder=new ItripHotelOrder();
         //从redis中获取用户信息
        String token = request.getHeader("token");
        ItripUser itripUser = (ItripUser)redisTemplate.opsForValue().get(token);
        System.out.println(itripUser.getId());
        //设置订单中用户id
         itripHotelOrder.setUserId(itripUser.getId());
         //设置旅馆id
        Long hotelId = bookingHotelVo.getHotelId();
        itripHotelOrder.setHotelId(bookingHotelVo.getHotelId());
        //设置订单类型
        itripHotelOrder.setOrderType(1);
        //设置订单号 不能重复，纯数字，时间+id
        //获取后缀
        Date date = new Date();
        long time = date.getTime();
        System.out.println(time);
        String suffix = Long.toString(time);
        //获取前缀
        Long roomId = bookingHotelVo.getRoomId();
        StringBuilder prefix = new StringBuilder(Long.toString(roomId));
        if(prefix.length()<6){
            for (int i=0;i<6-prefix.length();i++)
                prefix.append("0");
        }
        String orderId=prefix+suffix;
        itripHotelOrder.setOrderNo(orderId);
        //设置旅店id
        itripHotelOrder.setHotelId(bookingHotelVo.getHotelId());
        //设置旅店名称:暂无
        //设置roomid
        itripHotelOrder.setRoomId(bookingHotelVo.getRoomId());
        //设置房间剩余数量
        itripHotelOrder.setCount(bookingHotelVo.getCount());
        //设置预订天数
        long start = bookingHotelVo.getCheckInDate().getTime();
        long end = bookingHotelVo.getCheckOutDate().getTime();
        int times=(int)(end-start)/(1000*60*24);
        itripHotelOrder.setBookingDays(times);
        //设置预订的开始和结束天数
        itripHotelOrder.setCheckInDate(bookingHotelVo.getCheckInDate());
        itripHotelOrder.setCheckOutDate(bookingHotelVo.getCheckOutDate());
        //设置支付状态
        itripHotelOrder.setPayAmount(new BigDecimal(0));
        //设置支付金额 未设置
        //设置创建时间
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1=new Date();
        simpleDateFormat.format(date1);
        System.out.println(date1);
        itripHotelOrder.setCreationDate(date1);
        //设置orderStatus
        itripHotelOrder.setOrderStatus(1);

        //存入数据库
        int flag=hotelService.save(itripHotelOrder);
        System.out.println(flag);

        /*更新记录*/
        //创建一个记录对象
        ItripHotelTempStore itripHotelTempStore=new ItripHotelTempStore();
        //存入旅馆id
        itripHotelTempStore.setHotelId(bookingHotelVo.getHotelId().intValue());
        //存入房间id
        itripHotelTempStore.setRoomId(bookingHotelVo.getRoomId());
        //存入创建时间
        itripHotelTempStore.setRecordDate(date1);
        //存入记录数量
        //获取最新第Store
        int oldStore=hotelService.getRestRoom(bookingHotelVo.getHotelId().intValue(),bookingHotelVo.getRoomId().intValue());
        itripHotelTempStore.setStore(oldStore-1);
        //存入创建创建时间
        itripHotelTempStore.setCreationDate(date1);


        //将订单号及其相关信息存入redis，做过期处理
        //value里面放订单号和扣减的库存和房间号,这里默认为1
        redisTemplate.opsForValue().set("order:"+orderId+",1"+","+bookingHotelVo.getRoomId(),itripUser.getId(),1, TimeUnit.HOURS);



        //提交数据库
        int status=hotelService.saveRecord(itripHotelTempStore);
        System.out.println(itripHotelTempStore);

        return new ResponseDTO(100,"订单添加成功",itripHotelOrder);
    }





/*    //测试清理缓存
    @RequestMapping( "/clear" )

    public String clear(){
       hotelService.clear();
        return "清理";
    }*/


}
